package util.texture;

import javax.media.opengl.GL;
import javax.media.opengl.glu.GLU;

import com.sun.opengl.util.texture.Texture;

import util.BasicGraphicsJogl;

public class TextureDestinationWrapper
{
	private static void saveRenderState()
	{
		BasicGraphicsJogl basicGraphics = BasicGraphicsJogl.instance();
		GL gl = basicGraphics.getGL();
		gl.glPushAttrib(GL.GL_VIEWPORT_BIT);
		gl.glMatrixMode(GL.GL_PROJECTION);
		gl.glPushMatrix();
		gl.glMatrixMode(GL.GL_MODELVIEW);
	}
	private static void restoreRenderState()
	{
		BasicGraphicsJogl basicGraphics = BasicGraphicsJogl.instance();
		GL gl = basicGraphics.getGL();
		gl.glPopAttrib();
		gl.glMatrixMode(GL.GL_PROJECTION);
		gl.glPopMatrix();
		gl.glMatrixMode(GL.GL_MODELVIEW);
	}
	private static void unbindFrameBuffer()
	{
		BasicGraphicsJogl basicGraphics = BasicGraphicsJogl.instance();
		GL gl = basicGraphics.getGL();
		gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT,0);
		
	}
	public static void clearRenderTarget()
	{
		restoreRenderState();
		unbindFrameBuffer();
	}
	
	private Texture texture;
	private int frameBuffer;
	public TextureDestinationWrapper(Texture texture)
	{
		BasicGraphicsJogl basicGraphics = BasicGraphicsJogl.instance();
		this.texture = texture;
		int[] frameBuffers = new int[1];
		basicGraphics.getGL().glGenFramebuffersEXT(1, frameBuffers, 0);
		frameBuffer = frameBuffers[0];
	}
	public int getFrameBuffer()
	{
		return frameBuffer;
	}
	
	private void setViewportAndProjection()
	{
		BasicGraphicsJogl basicGraphics = BasicGraphicsJogl.instance();
		GL gl = basicGraphics.getGL();
		gl.glViewport(0,0,texture.getWidth(), texture.getHeight());
		gl.glMatrixMode(GL.GL_PROJECTION);
		gl.glLoadIdentity();
		final GLU glu = new GLU();
		glu.gluOrtho2D(0, texture.getWidth(), texture.getHeight(), 0);
		gl.glMatrixMode(GL.GL_MODELVIEW);
	}
	private void bindFrameBuffer()
	{
		BasicGraphicsJogl basicGraphics = BasicGraphicsJogl.instance();
		GL gl = basicGraphics.getGL();
		gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT,getFrameBuffer());
		gl.glFramebufferTexture2DEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_COLOR_ATTACHMENT0_EXT, GL.GL_TEXTURE_2D, texture.getTextureObject(), 0);
		
	}
	public void setRenderTarget()
	{
		saveRenderState();
		setViewportAndProjection();
		bindFrameBuffer();
	}
	public void destroy()
	{
		BasicGraphicsJogl basicGraphics = BasicGraphicsJogl.instance();
		GL gl = basicGraphics.getGL();
		gl.glDeleteFramebuffersEXT(1, new int[] {frameBuffer}, 0);
	}
	public void switchRenderTarget()
	{
		setViewportAndProjection();
		bindFrameBuffer();
	}

}
